package main

import (
	"fmt"
	"net/http"

	"fancy_web/data"
)

func login(w http.ResponseWriter, r *http.Request) {
	t := parseTemplateFiles("login.layout", "public.navbar", "login")
	t.Execute(w, nil)
}

func logout(w http.ResponseWriter, r *http.Request) {
	cookie, err := r.Cookie("_cookie")
	fmt.Println("logout cookie = ", cookie, err)
	if err != http.ErrNoCookie {
		data.DelSession(cookie.Value)
	}
	http.Redirect(w, r, "/", 302)
}

func signup(w http.ResponseWriter, r *http.Request) {
	generateHTML(w, nil, "login.layout", "public.navbar", "signup")
}

func signupAccount(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		return
	}

	user := data.User{
		Name:  r.PostFormValue("name"),
		Email: r.PostFormValue("email"),
		Pswd:  r.PostFormValue("password"),
	}
	err = user.Create()
	if err != nil {
		return
	}
	http.Redirect(w, r, "/login", 302)
}

func authenticate(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		return
	}

	user, err := data.GetUserByEmail(r.PostFormValue("email"))
	if err != nil {
		fmt.Println("authenticate err: ", err)
		return
	}
	fmt.Println("authenticate user = ", user)
	setUser(user.Id, &user)
	if user.Pswd == data.Encrypt(r.PostFormValue("password")) {
		session, err := user.CreateSession()
		if err != nil {
			fmt.Println(err)
			return
		}
		cookie := http.Cookie{
			Name:     "_cookie",
			Value:    session.Uuid,
			HttpOnly: true,
		}
		http.SetCookie(w, &cookie)
		http.Redirect(w, r, "/", 302)
		fmt.Println("auth success")
	} else {
		fmt.Println("auth fail")
		http.Redirect(w, r, "/login", 302)
	}
}
